package com.guigusuqi.commonutils.config;

import com.alibaba.fastjson.JSON;
import com.guigusuqi.commonutils.dto.ProceedingJoinPointDTO;
import com.guigusuqi.commonutils.utils.RedisCache;
import lombok.Data;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import java.time.Duration;

@Data
public class ScheduledTaskThread implements Runnable
{
    private ThreadLocal<ProceedingJoinPointDTO> joinPoint;

    @Resource
    private RedisCache redisCache = (RedisCache) SpringContextUtil.getBean("redisCache");

    public ScheduledTaskThread(ProceedingJoinPointDTO j)
    {
        this.joinPoint = ThreadLocal.withInitial(()-> j);
    }

    @Override
    @Async()
    public void run()
    {
        ProceedingJoinPointDTO proceedingJoinPointDTO = joinPoint.get();
        try {
            ProceedingJoinPoint joinPoint = proceedingJoinPointDTO.getJoinPoint();
            Object proceed = joinPoint.proceed();
            redisCache.setCacheObject(proceedingJoinPointDTO.getRedisKey(), JSON.toJSONString(proceed), Duration.ofMillis(proceedingJoinPointDTO.getExpire()));
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
